package com.software.project.service;

import com.software.project.entity.UserInfo;
import com.software.project.repository.UserInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService{
    @Autowired
    private UserInfoRepository userInfoRepository;
    //获取所有用户
    @Override
    public Page findUserInfo(UserInfo userInfo, Pageable pageable) {
        Specification<UserInfo> specification = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                //如果省份不为空 拼接上省份
                if (!StringUtils.isEmpty(userInfo.getProvince())) {
                    predicates.add(criteriaBuilder.like(root.get("province"),"%"+ userInfo.getProvince() +"%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Page page = userInfoRepository.findAll(specification,pageable);
        return page;
    }

    @Override
    public UserInfo findUserInfoByUserId(String userId) {
        log.debug("userId: {}", userId);
        Optional<UserInfo> optional = userInfoRepository.findById(userId);
        if (optional.isPresent()) {
            log.debug("UserInfo: {}", optional.get());
            return optional.get();
        } else {
            log.debug("UserInfo: {}", "null");
            return null;
        }
    }

    @Override
    public UserInfo createUserInfo(UserInfo userInfo) {
        UserInfo save = userInfoRepository.save(userInfo);
        log.debug("userInfo: {}", save);
        return save;
    }
}
